<template>
  <div class="edit-paper">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>编辑试卷</h3>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="paper-form"
      >
        <!-- 基本信息 -->
        <el-form-item label="试卷名称" prop="paperName">
          <el-input v-model="formData.paperName" placeholder="请输入试卷名称" />
        </el-form-item>

        <el-form-item label="考试时长" prop="duration">
          <el-input-number
            v-model="formData.duration"
            :min="1"
            :max="180"
            placeholder="请输入考试时长（分钟）"
          />
        </el-form-item>

        <el-form-item label="试卷说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入试卷说明"
          />
        </el-form-item>

        <!-- 题目选择 -->
        <div class="question-selection">
          <div class="selection-header">
            <span>题目选择</span>
            <el-button type="primary" @click="handleAddQuestion">
              <el-icon> <Plus /> </el-icon>添加题目
            </el-button>
          </div>
          <!-- 已选题目列表 -->
          <div class="selected-questions">
            <el-table
              :data="selectedQuestions"
              style="width: 100%"
              border
              @row-click="handlePreview"
            >
              <el-table-column type="index" min-width="55" label="序号" />
              <el-table-column
                prop="typeId"
                label="类型"
                min-width="85"
                sortable
              >
                <template #default="{ row }">
                  <el-tag :type="getTypeTag(row.typeId)"
                    >{{ getTypeText(row.typeId) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="content"
                label="题目内容"
                min-width="200"
                show-overflow-tooltip
                sortable
              />
              <el-table-column
                prop="difficulty"
                label="难度"
                min-width="150"
                sortable
              >
                <template #default="{ row }">
                  <el-rate v-model="row.difficulty" disabled :max="5" />
                </template>
              </el-table-column>
              <el-table-column
                prop="score"
                label="分值"
                min-width="150"
                sortable
              >
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.score"
                    :min="1"
                    :max="100"
                    size="small"
                    @click.native.stop="true"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="100" fixed="right">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    link
                    @click.native.stop="handleRemoveQuestion($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 是否公开 -->
        <el-form-item label="是否公开" prop="isPublic">
          <el-switch
              v-model="formData.isPublic"
              active-value="true"
              inactive-value="false"
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存修改</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 题目选择对话框 -->
    <el-dialog v-model="questionDialogVisible" title="" width="70%">
      <template #header="{ close, titleId, titleClass }">
        <div class="card-header">
          <h3>选择题目</h3>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索题目内容"
              class="search-input"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
            <el-select
              v-model="typeFilter"
              placeholder="题目类型"
              clearable
              @change="handleSearch"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-model="difficultyFilter"
              placeholder="难度"
              clearable
              @change="handleSearch"
            >
              <el-option
                v-for="item in difficultyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="questionList"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        @row-click="handlePreview"
      >
        <el-table-column type="selection" min-width="40" />
        <el-table-column type="index" min-width="55" label="序号" />
        <el-table-column prop="typeId" label="题型" min-width="85" sortable>
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.typeId)">{{
              getTypeText(row.typeId)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="题目内容"
          min-width="300"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          prop="difficulty"
          label="难度"
          min-width="160"
          sortable
        >
          <template #default="{ row }">
            <el-rate v-model="row.difficulty" disabled :max="5" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="questionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectQuestions">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <QuestionPreView ref="questionPreviewRef" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import {
  difficultyOptions,
  getDefaultScoreByType,
  getTypeTag,
  getTypeText,
  typeOptions,
} from "../../utils/utils";
import { paperApi } from "../../api/paperApi";
import { questionApi } from "../../api/questionApi";
import QuestionPreView from "../Question/QuestionPreView.vue";

const route = useRoute();
const router = useRouter();
const formRef = ref(null);
const loading = ref(false);
const questionDialogVisible = ref(false);
const searchQuery = ref("");
const typeFilter = ref("");
const difficultyFilter = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const questionList = ref([]);
const selectedQuestions = ref([]);
const tempSelectedQuestions = ref([]);

// 引用预览组件
const questionPreviewRef = ref(null);

// 预览题目
const handlePreview = (row) => {
  questionPreviewRef.value.handlePreview(row);
};

// 表单数据
const formData = reactive({
  paperName: "",
  description: "",
  duration: 120,
  isPublic: false, // 新增字段，默认不公开
});

// 表单验证规则
const rules = {
  paperName: [
    { required: true, message: "请输入试卷名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  duration: [{ required: true, message: "请输入考试时长", trigger: "blur" }],
};

// 获取试卷详情
const getPaperDetail = async () => {
  loading.value = true;
  try {
    const res = await paperApi.getPaperDetail(route.params.id);
    const paperData = res.result;
    formData.paperName = paperData.paperName;
    formData.duration = paperData.duration;
    formData.description = paperData.description;
    if (paperData.paperQuestions) {
      selectedQuestions.value = paperData.paperQuestions.map((q) => ({
        ...q,
        score: q.score || 5,
      }));
    }
  } catch (error) {
    console.error("获取试卷详情失败:", error);
    ElMessage.error("获取试卷详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取题目列表
const getQuestionList = async () => {
  loading.value = true;
  try {
    const res = await questionApi.getQuestionPage({
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      content: searchQuery.value,
      typeId: typeFilter.value,
      difficulty: difficultyFilter.value,
    });
    questionList.value = res.result.data;
    total.value = res.result.total;
  } catch (error) {
    console.error("获取题目列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getQuestionList();
};

// 打开题目选择对话框
const handleAddQuestion = () => {
  questionDialogVisible.value = true;
  getQuestionList();
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  tempSelectedQuestions.value = selection;
};

// 确认选择题目
const confirmSelectQuestions = () => {
  // 过滤掉已选择的题目
  const newQuestions = tempSelectedQuestions.value.filter(
    (question) =>
      !selectedQuestions.value.some((q) => q.questionId === question.questionId)
  );
  newQuestions.forEach((q) => (q.score = getDefaultScoreByType(q.typeId)));
  selectedQuestions.value.push(...newQuestions);
  questionDialogVisible.value = false;
};

// 移除已选题目
const handleRemoveQuestion = (index) => {
  selectedQuestions.value.splice(index, 1);
};

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  getQuestionList();
};

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getQuestionList();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (selectedQuestions.value.length === 0) {
      ElMessage.warning("请至少选择一道题目");
      return;
    }

    const paperData = {
      ...formData,
      paperQuestions: selectedQuestions.value.map((q) => ({
        relatedId: q.relatedId,
        questionId: q.questionId,
        score: q.score,
        paperId: route.params.id,
      })),
      paperId: route.params.id,
    };

    await paperApi.updatePaper(paperData);

    ElMessage.success("修改成功");
    router.push("/paper");
  } catch (error) {
    console.error("修改试卷失败:", error);
  }
};

onMounted(() => {
  getPaperDetail();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 20px;
}

.edit-paper {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.paper-form {
  max-width: 900px;
  margin: 0 auto;
}

.selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.selection-header span {
  font-size: 14px;
  margin-left: 32px;
  color: var(--el-text-color-regular);
}

.search-input {
  width: 300px;
}

.selected-questions h4 {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.question-selection {
  margin-bottom: 10px;
}

.selected-questions {
  margin-left: 100px;
}
</style>
